#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Agent-RAG系统
Agent嵌套RAG的完整系统
"""

import json
import logging
from typing import Dict, Any, List, Optional
from flask import Flask, request, jsonify
from flask_cors import CORS
from rag_agent import RAGAgent, AgentState
from rag_tool import RAGToolManager

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建Flask应用
app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 全局Agent实例
rag_agent = None
tool_manager = None

def init_agent_rag_system():
    """初始化Agent-RAG系统"""
    global rag_agent, tool_manager
    
    try:
        # 初始化Agent
        rag_agent = RAGAgent("人与自然关系专家")
        
        # 初始化工具管理器
        tool_manager = RAGToolManager()
        
        logger.info("Agent-RAG系统初始化完成")
        return True
        
    except Exception as e:
        logger.error(f"Agent-RAG系统初始化失败: {e}")
        return False

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        "status": "healthy",
        "message": "Agent-RAG系统运行正常",
        "version": "1.0.0"
    })

@app.route('/api/agent/chat', methods=['POST'])
def agent_chat():
    """
    Agent对话接口
    
    请求格式:
    {
        "message": "用户消息",
        "session_id": "会话ID"  # 可选
    }
    
    响应格式:
    {
        "status": "success",
        "response": "Agent回答",
        "tools_used": ["tool1", "tool2"],
        "confidence": 0.85,
        "metadata": {...}
    }
    """
    try:
        data = request.get_json()
        
        if not data or 'message' not in data:
            return jsonify({
                "status": "error",
                "message": "缺少message参数"
            }), 400
        
        user_message = data['message'].strip()
        session_id = data.get('session_id', 'default')
        
        if not user_message:
            return jsonify({
                "status": "error",
                "message": "消息不能为空"
            }), 400
        
        # 处理用户消息
        response = rag_agent.process_user_input(user_message)
        
        return jsonify({
            "status": "success",
            "response": response.content,
            "tools_used": response.tools_used,
            "confidence": response.confidence,
            "metadata": response.metadata,
            "session_id": session_id
        })
        
    except Exception as e:
        logger.error(f"Agent对话失败: {e}")
        return jsonify({
            "status": "error",
            "message": f"对话失败: {str(e)}"
        }), 500

@app.route('/api/agent/status', methods=['GET'])
def get_agent_status():
    """获取Agent状态接口"""
    try:
        status = rag_agent.get_agent_status()
        
        return jsonify({
            "status": "success",
            "agent_status": status
        })
        
    except Exception as e:
        logger.error(f"获取Agent状态失败: {e}")
        return jsonify({
            "status": "error",
            "message": f"获取状态失败: {str(e)}"
        }), 500

@app.route('/api/agent/history', methods=['GET'])
def get_conversation_history():
    """获取对话历史接口"""
    try:
        history = rag_agent.get_conversation_history()
        
        return jsonify({
            "status": "success",
            "history": history,
            "total_messages": len(history)
        })
        
    except Exception as e:
        logger.error(f"获取对话历史失败: {e}")
        return jsonify({
            "status": "error",
            "message": f"获取历史失败: {str(e)}"
        }), 500

@app.route('/api/agent/clear', methods=['POST'])
def clear_conversation():
    """清空对话历史接口"""
    try:
        rag_agent.clear_conversation_history()
        
        return jsonify({
            "status": "success",
            "message": "对话历史已清空"
        })
        
    except Exception as e:
        logger.error(f"清空对话历史失败: {e}")
        return jsonify({
            "status": "error",
            "message": f"清空失败: {str(e)}"
        }), 500

@app.route('/api/tools/list', methods=['GET'])
def list_tools():
    """列出所有工具接口"""
    try:
        tools_schema = tool_manager.get_tools_schema()
        
        return jsonify({
            "status": "success",
            "tools": tools_schema
        })
        
    except Exception as e:
        logger.error(f"列出工具失败: {e}")
        return jsonify({
            "status": "error",
            "message": f"列出工具失败: {str(e)}"
        }), 500

@app.route('/api/tools/execute', methods=['POST'])
def execute_tool():
    """
    执行工具接口
    
    请求格式:
    {
        "tool_name": "knowledge_base_search",
        "parameters": {
            "query": "人与自然",
            "top_k": 5
        }
    }
    """
    try:
        data = request.get_json()
        
        if not data or 'tool_name' not in data:
            return jsonify({
                "status": "error",
                "message": "缺少tool_name参数"
            }), 400
        
        tool_name = data['tool_name']
        parameters = data.get('parameters', {})
        
        # 执行工具
        result = tool_manager.execute_tool(tool_name, **parameters)
        
        return jsonify({
            "status": "success" if result.success else "error",
            "tool_name": tool_name,
            "result": result.data,
            "message": result.message,
            "metadata": result.metadata
        })
        
    except Exception as e:
        logger.error(f"执行工具失败: {e}")
        return jsonify({
            "status": "error",
            "message": f"执行工具失败: {str(e)}"
        }), 500

@app.route('/api/agent/batch_chat', methods=['POST'])
def batch_agent_chat():
    """
    批量Agent对话接口
    
    请求格式:
    {
        "messages": ["消息1", "消息2", "消息3"]
    }
    """
    try:
        data = request.get_json()
        
        if not data or 'messages' not in data:
            return jsonify({
                "status": "error",
                "message": "缺少messages参数"
            }), 400
        
        messages = data['messages']
        
        if not isinstance(messages, list) or not messages:
            return jsonify({
                "status": "error",
                "message": "messages必须是非空列表"
            }), 400
        
        # 批量处理消息
        results = []
        for i, message in enumerate(messages):
            try:
                response = rag_agent.process_user_input(message)
                results.append({
                    "index": i,
                    "message": message,
                    "response": response.content,
                    "tools_used": response.tools_used,
                    "confidence": response.confidence,
                    "success": True
                })
            except Exception as e:
                results.append({
                    "index": i,
                    "message": message,
                    "error": str(e),
                    "success": False
                })
        
        return jsonify({
            "status": "success",
            "results": results,
            "total_messages": len(messages),
            "successful": len([r for r in results if r["success"]])
        })
        
    except Exception as e:
        logger.error(f"批量Agent对话失败: {e}")
        return jsonify({
            "status": "error",
            "message": f"批量对话失败: {str(e)}"
        }), 500

@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return jsonify({
        "status": "error",
        "message": "接口不存在"
    }), 404

@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    return jsonify({
        "status": "error",
        "message": "服务器内部错误"
    }), 500

def main():
    """启动Agent-RAG系统"""
    # 初始化系统
    if not init_agent_rag_system():
        logger.error("Agent-RAG系统初始化失败，退出")
        return
    
    # 启动Flask应用
    logger.info("启动Agent-RAG系统...")
    logger.info("API接口:")
    logger.info("  GET  /health - 健康检查")
    logger.info("  POST /api/agent/chat - Agent对话")
    logger.info("  GET  /api/agent/status - 获取Agent状态")
    logger.info("  GET  /api/agent/history - 获取对话历史")
    logger.info("  POST /api/agent/clear - 清空对话历史")
    logger.info("  POST /api/agent/batch_chat - 批量Agent对话")
    logger.info("  GET  /api/tools/list - 列出所有工具")
    logger.info("  POST /api/tools/execute - 执行工具")
    
    app.run(host='0.0.0.0', port=5002, debug=True)

if __name__ == "__main__":
    main()
